package com.cp.oss.service.impl;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.cp.oss.service.FileService;
import com.cp.oss.util.OssProperties;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.UUID;

/**
 * @author ming
 * @create 2022/8/1
 * @description:
 */
@Service
@Slf4j
public class FileServiceImpl implements FileService {

    @Override
    public String fileUpload(InputStream inputStream, String module, String fileName) {
        OSS ossClient = new OSSClientBuilder()
                .build(OssProperties.ENDPOINT, OssProperties.KEY_ID, OssProperties.KEY_SECRET);
        if(!ossClient.doesBucketExist(OssProperties.BUCKET_NAME)){
            ossClient.createBucket(OssProperties.BUCKET_NAME);
            ossClient.setBucketAcl(OssProperties.BUCKET_NAME, CannedAccessControlList.PublicRead);
        }
        //目录结构 /avatar/2022/08/01/uuid.fileName的扩展名
        String timeFolder = new DateTime().toString("/yyyy/MM/dd/");
        fileName = UUID.randomUUID().toString()+fileName.substring(fileName.lastIndexOf("."));
        String key = module+timeFolder+fileName;
        ossClient.putObject(OssProperties.BUCKET_NAME,key,inputStream);
        ossClient.shutdown();
        String tempEndPoint = OssProperties.ENDPOINT.substring(OssProperties.ENDPOINT.lastIndexOf("/")+1);
        return "https://"+OssProperties.BUCKET_NAME+"."+tempEndPoint+"/"+key;
    }

    @Override
    public void removeFile(String url) {
        OSS ossClient = new OSSClientBuilder()
                .build(OssProperties.ENDPOINT, OssProperties.KEY_ID, OssProperties.KEY_SECRET);
        // "https://srb-file-minghui.oss-cn-beijing.aliyuncs.com/avatar/me.jpg";
        String host = "https://"+OssProperties.BUCKET_NAME+"."+OssProperties.ENDPOINT+"/";
        //要删除的传入的值为 /avatar/me.jpg
        ossClient.deleteObject(OssProperties.BUCKET_NAME,url.substring(host.length()));
        ossClient.shutdown();
    }
}
